<?php

namespace App\Library\Service;

use App\Library\Logic\AreaLogic;
use App\Library\Requests\Area\AreaInfoRequest;
use App\Library\Requests\Base\IdRequest;
use Illuminate\Http\JsonResponse;

class AreaService extends BaseService
{
    public function __construct(AreaLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     *
     * @param AreaInfoRequest $request
     * @return JsonResponse
     *
     */
    public function areaInfo(AreaInfoRequest $request): JsonResponse
    {
        return success($this->logic->areaInfo($request));
    }

    public function all(): string
    {
        $area = $this->logic->alls();
        $level3 = $this->logic->level3();
        foreach ($area as $k1 => $v1) {
            foreach ($v1['child'] as $k2 => $v2) {
                $child = [];
                unset($v2['parent_id']);
                foreach ($level3 as $k3 => $v3) {
                    if ($v2['id'] === $v3['parent_id']) {
                        unset($v3['parent_id']);
                        unset($level3[$k3]);
                        $child[] = $v3;
                    }
                }
                $v2['child'] = $child;
                $v1['child'][$k2] = $v2;
            }
            $area[$k1] = $v1;
        }
        return json_encode($area);
    }
}
